<template>
<div v-if="role=='teacher'" >
  <el-card class="box-card">
    <div shadow="always" class="card-header">
      <span style="font-size: x-large;">历史作业</span>
      <el-button class="button" type="primary" round @click="clickHandler">新建作业</el-button>
      <el-dialog v-model="dialogFormVisible" title="新建作业">
        <el-form :model="form">
          <el-form-item label="标题" :label-width="formLabelWidth">
            <el-input v-model="form.title" autocomplete="off" />
          </el-form-item>
          <el-form-item label="内容" :label-width="formLabelWidth">
            <el-input v-model="form.content" autocomplete="off" type="textarea"
              :autosize="{ minRows: 4, maxRows: 6 }" />
          </el-form-item>
          <el-form-item label="时间" :label-width="formLabelWidth">
            <el-date-picker v-model="value1" type="datetimerange" range-separator="To" start-placeholder="Start date"
              end-placeholder="End date" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="newTask()">发布</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-card>

  <el-table :data="tableData" height="450" style="width: 100%" @row-dblclick="checkTask">
    <el-table-column prop="title" label="标题" />
    <el-table-column prop="sender" label="作者" width="200rpx" />
    <el-table-column prop="time" label="时间" />
    <el-table-column align="right">
      <!-- <template #header>
        <el-button class="button" size="small" type="success" round>未过期</el-button>
        <el-button class="button" size="small" type="warning" round>已过期</el-button>
      </template> -->
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row)" style="background:white;color:black">修改</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
    <el-dialog v-model="dialogFormVisible2" title="修改作业">
    <el-form :model="form">
      <el-form-item label="标题" :label-width="formLabelWidth">
        <el-input v-model="form.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="内容" :label-width="formLabelWidth">
        <el-input v-model="form.content" autocomplete="off" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" />
      </el-form-item>
      <el-form-item label="时间" :label-width="formLabelWidth">
        <el-date-picker v-model="value2" type="datetimerange" range-separator="To" start-placeholder="Start date"
          end-placeholder="End date" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取消</el-button>
        <el-button type="primary" @click="editTask()">修改</el-button>
      </span>
    </template>
  </el-dialog>
  </div>
  <div v-if="role=='student'">
  <h4>我的作业</h4>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="title" label="标题" />
    <el-table-column prop="sender" label="作者" width="200rpx" />
    <el-table-column prop="time" label="时间" />
    <el-table-column align="right">
      <template #default="scope">
        <el-button v-if="tableData[scope.$index].state" size="small" @click="studentEdit(scope.row)" style="background:white;color:black">进入</el-button>
      <span v-if="!tableData[scope.$index].state">已过期</span>
      </template>
    </el-table-column>
  </el-table>
</div>
</template>

<script>
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { queryAllByCourseId, add, deleteTaskById, edit, } from "../../api/task.js";
import { mapGetters } from 'vuex';
export default {
  // 数据源
  data() {
    return {
      dialogFormVisible: false,
      dialogFormVisible2: false,
      formLabelWidth: '50px',
      form: {
        title: '',
        content: '',
        taskId: '',
        courseId: '',
        sender: 'tt',
        sendTime: '',
        deadLine: ''
      },
      value1: [
        new Date(),
        new Date(2022, 11, 31, 23, 59)
      ],
      value2: [
        new Date(),
        new Date()
      ],
      courseId: "",
      tableData: []
    };
  },
  //生命周期函数---
  mounted() {
    this.courseId = this.getParams();
    this.getData();
  },
  //基本方法
  methods: {
    studentEdit(row){
      // console.log(row)
      this.$router.push('/user/mycourse/answer?courseId='+this.courseId+'&taskId='+row.taskId)
    },
    checkTask(row) {
      // console.log(row)
      this.$router.push('/user/mycourse/work?courseId='+this.courseId+'&taskId='+row.taskId)
    },
    editTask() {
      this.dialogFormVisible2 = false
      this.form.sendTime = this.value2[0]
      this.form.deadLine = this.value2[1]
      console.log(this.form)
      edit(this.form).then((res) => {
        if (res.code == 200) {
          ElMessage({
            type:'success',
            message:'修改成功'
          })
          this.getData()
        } else {
             ElMessage({
            type:'error',
            message:'修改失败'
          })
        }
      })
    },
    handleEdit(row) {
      this.dialogFormVisible2 = true
      this.value2[0] = new Date(row.time.split('~')[0])
      this.value2[1] = new Date(row.time.split('~')[1])
      console.log(this.value2[0])
      console.log(this.value2[1])
      this.form.title = row.title
      this.form.content = row.content
      this.form.taskId = row.taskId
      this.form.courseId = row.courseId
    },
    handleDelete(row) {
      deleteTaskById(row.taskId).then((res) => {
        if (res.code == 200) {
          ElMessage({
            type:'success',
            message:'删除成功'
          })
          this.getData()
        } else {
          ElMessage({
            type:'error',
            message:'删除失败'
          })
        }
      })
      //console.log(index)//下标
      //console.log(row)//表格实体 title sender time
    },
    clickHandler(evt) {
      var that = this
      that.dialogFormVisible = true
      let target = evt.target;
      if (target.nodeName == "SPAN") {
        target = evt.target.parentNode;
      }
      target.blur();
      that.form.title = ""
      that.form.content = ""
    },
    newTask() {
      var that = this
      that.dialogFormVisible = false
      that.form.sendTime = that.value1[0]
      that.form.deadLine = that.value1[1]
      that.form.sender = 'tt'//从当前登录用户获取
      that.form.courseId = that.courseId
      add(that.form).then((res) => {
        if (res.code == 200) {
          //console.log(res.data)
          that.getData()
        } else {
             ElMessage({
            type:'error',
            message:'啊哦，失败'
          })
        }
      })
    },
    formatDate(now) {
      var year = now.getFullYear();  //取得4位数的年份
      var month = this.addzoer(now.getMonth() + 1);  //取得日期中的月份，其中0表示1月，11表示12月
      var date = this.addzoer(now.getDate());      //返回日期月份中的天数（1到31）
      var hour = this.addzoer(now.getHours());     //返回日期中的小时数（0到23）
      var minute = this.addzoer(now.getMinutes()); //返回日期中的分钟数（0到59）
      var second = this.addzoer(now.getSeconds()); //返回日期中的秒数（0到59）
      return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    },
    addzoer(timE) {
      if (timE < 10) {
        return '0' + timE
      } else {
        return timE
      }
    },
    getParams() {
      const route = useRoute();
      let courseId = route.query.courseId;
      return courseId;
    },
    getData() {
      var that = this
      that.tableData = []
      queryAllByCourseId(that.courseId).then((res) => {
        if (res.code == 200) {
        //  console.log(res.data)
          for (var i = 0; i < res.data.length; i++) {
            var task = {
              title: "",
              sender: "",
              time: "",
              taskId: "",
              courseId: "",
              content: "",
              state:true
            }
            task.title = res.data[i].title;
            task.sender = res.data[i].sender;
            task.time = that.formatDate(new Date(res.data[i].sendTime)) + "~" + that.formatDate(new Date(res.data[i].deadLine));
            if(that.formatDate(new Date())>that.formatDate(new Date(res.data[i].deadLine))){
             // console.log("已过期")
              task.state=false;
            }
            task.taskId = res.data[i].taskId;
            task.courseId = res.data[i].courseId;
            task.content = res.data[i].content;
            that.tableData.push(task);
          }
         // console.log(that.tableData)
        } else {
          ElMessage({
            type: "error",
            message: "获取作业信息失败",
          });
        }
      })
    }
  },
  //计算类型方法和其他方法的区别：有缓存。以内存换时间，适用于频繁使用的计算
  computed :{
    ...mapGetters({
      role:'getRole',
    })
  },
};
</script>

<style   scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-select {
  width: 300px;
}

.el-input {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>